//配置路由
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";

Vue.use(VueRouter);

// 先备份一份 push 方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//重新push方法 location是传递的参数（跳专路径、和参数）

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    //使用call 是要VueRouter 实例来调用push方法 而不是 window
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    //使用call 是要VueRouter 实例来调用push方法 而不是 window
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

const router = new VueRouter({
  routes,
  // 当切换到新路由时，想要页面滚到顶部
  scrollBehavior(to, from, savedPosition) {
    return { y: 0 };
  },
});

//路由守卫
router.beforeEach(async (to, from, next) => {
  const token = store.state.register.user_token;
  const name = store.state.register.userInfo.name;
  //登录
  if (token) {
    //去login 或 register
    if (to.path == "/login" || to.path == "/register") {
      next("/home");
    } else {
      //不去login
      if (name) {
        //有name 直接放行
        next();
      } else {
        try {
          //没有name 就去获取userInfo
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          //如果失败 则说明token 过期,需退出登录重新登录
          await store.dispatch("logout");
          next(`/login?redirect=${to.path}`);
        }
      }
    }
  } else {
    //未登录 ;不能去交易相关、不能去支付相关、不能去个人中心
    let path = to.path;
    if (path == "/trade" || path == "/pay" || path.indexOf("/center") !== -1) {
      next(`/login?redirect=${path}`);
    } else {
      next();
    }
  }
});

export default router;
